package com.kehongborui.staff.controller;

import com.kehongborui.staff.entity.Staff;
import com.kehongborui.staff.model.Condition;
import com.kehongborui.staff.model.Page;
import com.kehongborui.staff.service.IStaffService;
import com.kehongborui.staff.service.impl.StaffService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * @Description:   员工信息表的操作
 * @Author:         XCQ
 * @email:          mr_xcq@163.com
 * @CreateDate:    2018-11-29 15:23
 * @UpdateUser:    username
 * @UpdateDate:    xxxx-xx-xx
 * @UpdateRemark:  修改内容
 * @Version:         1.0
*/
public class StaffController extends HttpServlet {
    private IStaffService iStaffService = new StaffService();
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 中文乱码解决
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html:utf-8");
        // 获取路径
        String uri = req.getRequestURI();
        // 根据不同请求路径，完成相应操作及跳转
        if (uri.contains("delete")) {      // 删除操作
            deleteById(req ,resp);
        } else if (uri.contains("list")) { // 查询相关
            try {
                queryAll(req, resp);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        } else if (uri.contains("updateandaddpage")) { // 进入修改或新增员工信息界面
                getUpdateAndAddPage(req, resp);
        } else if (uri.contains("addandupdatedata")) { // 提交修改或新增员工信息
            try {
                updateAndCreate(req, resp);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
    }
/**
 * @Description:    进入修改或新增员工信息界面，根据是否传递 id 参数，修改需传递 id 参数
 * @Param:
 * @return:
 * @Author:          XCQ
 * @email:           mr_xcq@163.com
 * @CreateDate:     2018/11/29 22:49
*/
    private void getUpdateAndAddPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int flag = 0;
        // 获取 id 参数
        String idString = req.getParameter("id");
        // 利用字符串是否为空来判断 id 参数是否存在
        if (idString != null && idString != "") {
            flag = 1;  // id 参数存在即表明修改，利用flag == 1 标志
            Staff staff = iStaffService.queryById(Integer.parseInt(idString));
            req.setAttribute("staff", staff);
        } else {
            flag = 2;  // id 参数不存在即表明新增，利用flag == 2 标志
        }
        // 将flag参数传递到jsp中，从而在页面完成新增及修改的区分
        req.setAttribute("flag", flag);
        req.getRequestDispatcher("/WEB-INF/view/updateandaddpage.jsp").forward(req, resp);
    }

    /**
     * @Description:    查询方法
     * @Param:
     * @return:
     * @Author:          XCQ
     * @email:           mr_xcq@163.com
     * @CreateDate:     2018/11/29 15:35
    */
    public void queryAll(HttpServletRequest req, HttpServletResponse resp) throws ParseException, ServletException, IOException {
        // 获取查询条件
        String staffName = req.getParameter("staff_name");
        String staffNumString = req.getParameter("staff_num");
        String staffDepartment = req.getParameter("staff_department");
        String joinedTimeString = req.getParameter("joined_time");
        String currentPageString = req.getParameter("current_page");
        String pageSizeString = req.getParameter("page_size");
        // 创建封装类
        Page page = new Page();
        Condition condition = new Condition();
        // 判断查询条件是否存在
        if (staffName != null && !staffName.equals("")) {
            condition.setStaffName(staffName.trim());
        }
        if (staffNumString != null && !staffNumString.equals("")) {
            condition.setStaffNum(Integer.parseInt(staffNumString.trim()));
        }
        if (staffDepartment != null && !staffDepartment.equals("")) {
            condition.setStaffDepartment(staffDepartment.trim());
        }
        if (joinedTimeString != null && !joinedTimeString.equals("")) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yy-MM-dd");
            Long timeUtil = simpleDateFormat.parse(joinedTimeString).getTime();
            Date joinedTime = new Date(timeUtil);
            condition.setJoinedTime(joinedTime);
        }
        if (currentPageString != null && !currentPageString.equals("")) {
            int currentPage = Integer.parseInt(currentPageString);
            page.setCurrentPage(currentPage);
        }
        if (pageSizeString != null && !pageSizeString.equals("")) {
            int pageSize = Integer.parseInt(pageSizeString);
            page.setPageSize(pageSize);
        }
        // 调用Service层的方法，完成查询
        List<Staff> staffs = iStaffService.queryAll(condition ,page);
        Page pageResult = iStaffService.queryNum(condition);
        // 将相关参数传递到jsp页面
        req.setAttribute("staffs", staffs);           // 查询结果显示
        req.setAttribute("pageResult", pageResult);   // 分页查询结果相关的显示
        req.setAttribute("condition", condition);     // 查询条件回显
        req.setAttribute("page", page);               // currentPage的回显
        req.getRequestDispatcher("/WEB-INF/view/listpage.jsp").forward(req, resp);

    }
    /**
     * @Description:    根据 id 删除
     * @Param:
     * @return:
     * @Author:          XCQ
     * @email:           mr_xcq@163.com
     * @CreateDate:     2018/11/29 17:56
    */
    public void deleteById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int id = Integer.parseInt(req.getParameter("id"));
        String result = iStaffService.deleteById(id);
        resp.sendRedirect("/staff/list");
        System.out.println(result);
    }
    /**
     * @Description:    删除和新增方法
     * @Param:
     * @return:
     * @Author:          XCQ
     * @email:           mr_xcq@163.com
     * @CreateDate:     2018/11/29 17:56
    */
    public void updateAndCreate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, ParseException {
        int flag = 0;              // 新增或修改判断标志位
        String result = null;
        Staff staff = new Staff();
        // 获取参数
        String idString = req.getParameter("id");
        int staffNum = Integer.parseInt(req.getParameter("staff_num"));
        String staffName = req.getParameter("staff_name");
        String staffDepartment = req.getParameter("staff_department");
        String staffGender = req.getParameter("staff_gender");
        String staffAgeString = req.getParameter("staff_age");
        Double staffWeight = Double.parseDouble(req.getParameter("staff_weight"));
        Double staffHeight = Double.parseDouble(req.getParameter("staff_height"));
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yy-MM-dd");
        String joinedTimeString = req.getParameter("joined_time");
        Long timeUtil = simpleDateFormat.parse(joinedTimeString).getTime();
        Date joinedTime = new Date(timeUtil);
        // 将参数封装到staff对象
        staff.setStaffNum(staffNum);
        staff.setStaffName(staffName);
        staff.setStaffDepartment(staffDepartment);
        staff.setStaffGender(staffGender);
        staff.setStaffAge(Integer.parseInt(staffAgeString));
        staff.setStaffWeight(staffWeight);
        staff.setStaffHeight(staffHeight);
        staff.setJoinedTime(joinedTime);
        // 利用字符串是否为空来判断 id 参数是否存在
        if (idString != null && idString != "") {
            flag = 1;  // id 参数存在即表明修改，利用flag == 1 标志,调用修改相关方法
            int id = Integer.parseInt(idString);
            staff.setId(id);
            staff.setUpdate_time(new Date(System.currentTimeMillis()));
            result = iStaffService.updateById(staff);
        } else {
            flag = 2;  // id 参数存在即表明新增，利用flag == 2 标志,调用新增相关方法
            staff.setCreateTime(new Date(System.currentTimeMillis()));
            result = iStaffService.create(staff);
        }
        resp.sendRedirect("/staff/list");
        System.out.println(result);
    }
}
